package com.jcj.monitorevent;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 服务器端I/O处理类,连接监测
 */
@ChannelHandler.Sharable
public class HandlerServerMonitorEvent extends ChannelInboundHandlerAdapter {

    //通道数组,保存所有注册到EventLoop的通道
    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //处理接收到的数据,并反馈消息到客户端
        ByteBuf in = (ByteBuf) msg;
        System.out.println("收到客户端发过来的消息: " + in.toString(CharsetUtil.UTF_8));

        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss SSS");//设置日期格式
        String strDate = df.format(new Date());
        //写入并发送信息到远端(客户端)
        ctx.writeAndFlush(Unpooled.copiedBuffer("这是服务器端在Read方法中反馈的消息 " + strDate + "\r\n", CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //出现异常的时候执行的动作(打印并关闭通道)
        cause.printStackTrace();
        ctx.close();
    }

    /**
     * 新建立连接时触发的动作
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        //System.out.println("打印channel:"+channel);
        //System.out.println("运行类型:"+channel.getClass());
        System.out.println("客户端: " + channel.remoteAddress() + "已连接上来");
        channels.add(channel);
    }

    /**
     * 连接断开时触发的动作
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("客户端: " + channel.remoteAddress() + "已断开");
        channels.remove(channel);
    }

    /**
     * 通道处于活动状态触发的动作,该方法只会在通道建立时调用一次
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("客户端: " + channel.remoteAddress() + "在线");
        //写入并发送信息到远端,(通道建立成功往客户端发送一段字符串)
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss SSS");//设置日期格式
        String strDate = df.format(new Date());
        ctx.writeAndFlush(Unpooled.copiedBuffer("这是服务器端在Active方法中反馈的消息: " + strDate + "\r\n", CharsetUtil.UTF_8));
    }

    /**
     * 通道处于非活动状态触发的动作,该方法只会在通道失效时调用一次
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("客户端: " + channel.remoteAddress() + "掉线");
    }
}









































